//
//  photoBrowserController.swift
//  DSWeibo
//
//  Created by J on 16/5/2.
//  Copyright © 2016年 J. All rights reserved.
//

import UIKit
import SVProgressHUD
private let reuseIdentifier = "Cell"


class photoBrowserController: UIViewController {

    
    var currentIndex: Int?
    var pictureURLS :[NSURL]?
    
  
    init(index:Int,urls:[NSURL]){
        super.init(nibName: nil, bundle: nil)

        currentIndex = index
        pictureURLS = urls
    }
    
 
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        
        
        //2.布局子控件
        let  superView = view
        let  padding = 10
        closeBtn.snp_makeConstraints { (make) in
            make.left.equalTo(superView).offset(padding)
            make.bottom.equalTo(superView).offset(-padding)
            make.size.equalTo(CGSize(width: 70, height: 35))
        }
        
        
        saveBtn.snp_makeConstraints { (make) in
            make.size.equalTo(closeBtn)
            make.right.equalTo(superView).offset(-padding)
            make.bottom.equalTo(closeBtn)
        }
        
        
        collectionView.snp_makeConstraints { (make) in
            make.edges.equalTo(superView)
        }
        
        
    }
    
    private func setupUI(){
        //1.添加子控件
        view.addSubview(collectionView)
        view.addSubview(closeBtn)
        view.addSubview(saveBtn)


    
        
    }
    
    
    //MARK: --懒加载
    
    private lazy var closeBtn :UIButton = {
       let btn = UIButton()
        btn.setTitle("关闭", forState: UIControlState.Normal)
        btn.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
        btn.backgroundColor = UIColor.blackColor()
        btn.addTarget(self, action: #selector(photoBrowserController.close), forControlEvents: UIControlEvents.TouchUpInside)
        return btn
        
    }()
    
    private lazy var saveBtn :UIButton = {
        let btn = UIButton()
        btn.setTitle("保存", forState: UIControlState.Normal)
        btn.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
        btn.backgroundColor = UIColor.blackColor()
        btn.addTarget(self, action: #selector(photoBrowserController.save), forControlEvents: UIControlEvents.TouchUpInside)

        return btn
    }()
    
    private static var flowLayout = photoBrowserControllerLayout()
    private lazy var collectionView :UICollectionView = {
        let collection  = UICollectionView(frame: CGRectZero, collectionViewLayout: flowLayout)
        collection.delegate = self
        collection.dataSource = self
        collection.registerClass(photoBrowserCell.self, forCellWithReuseIdentifier: reuseIdentifier)
        return collection
    }()
    
    func close(){
        self.dismissViewControllerAnimated(true) {
            
        }
    }
    
    
    
    //保存图片到相册
    func save(btn:UIButton){
        //1.拿到当前正在显示的cell
        let indexPath =  collectionView.indexPathsForVisibleItems().last!
       let cell = collectionView.cellForItemAtIndexPath(indexPath) as! photoBrowserCell
        
        //2.保存图片
        let image = cell.iconView.image
        
        //保存图片
        UIImageWriteToSavedPhotosAlbum(image!, self, #selector(photoBrowserController.image(_:didFinishSavingWithError:contextInfo:)), nil)
    }
    
    func image(image:UIImage, didFinishSavingWithError error:NSError? ,contextInfo info:AnyObject){

        if error != nil {
            SVProgressHUD.showErrorWithStatus("保存失败")
            SVProgressHUD.setDefaultMaskType(SVProgressHUDMaskType.Black)
        }else{
            SVProgressHUD.showSuccessWithStatus("保存成功")
            SVProgressHUD.setDefaultMaskType(SVProgressHUDMaskType.Black)
        }
}

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
    
    
   

}



//协议拓展
extension photoBrowserController:UICollectionViewDelegate,UICollectionViewDataSource,photoBrowserCellProtocol{
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return pictureURLS!.count ?? 0
    }
    
    
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! photoBrowserCell
        cell.imageURL = pictureURLS?[indexPath.row]
        cell.photoBrowserCellDelegate = self
        return cell
    }
    
    //dismiss
    func photoCellDidClose(cell: photoBrowserCell) {
        self.dismissViewControllerAnimated(true) { 
            
        }
    }

}







//布局对象
class  photoBrowserControllerLayout: UICollectionViewFlowLayout{
    
    override func prepareLayout() {
        itemSize = UIScreen.mainScreen().bounds.size
        minimumLineSpacing = 0
        minimumInteritemSpacing = 0
        scrollDirection = UICollectionViewScrollDirection.Horizontal
        collectionView?.showsVerticalScrollIndicator = false
        collectionView?.showsHorizontalScrollIndicator = false
        collectionView?.pagingEnabled = true
        collectionView?.bounces = false        
    }
    
}

